<?php

require_once dirname(__FILE__) . '/../lib/videoGroupGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/videoGroupGeneratorHelper.class.php';

/**
 * videoGroup actions.
 *
 * @package    iEasy
 * @subpackage videoGroup
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class videoGroupActions extends autoVideoGroupActions {

    //新建视频组
    public function executeNew(sfWebRequest $request) {
        parent::executeNew($request);
        $this->videos = $this->getAllVideos();
        $this->group_videos = array();
    }

    //编辑视频组
    public function executeEdit(sfWebRequest $request) {
        parent::executeEdit($request);
        $this->videos = $this->getAllVideos();
        $this->group_videos = $this->getGroupVideos();
    }

    //删除视频组
    public function executeDelete(sfWebRequest $request) {
        $videoGroupToBeDelete = $this->getRoute()->getObject();
        //标记删除
        $videoGroupToBeDelete->setStatusId(1006);
        $videoGroupToBeDelete->save();
        $this->redirect('@video_group');
    }

    public function executeIndex(sfWebRequest $request) {
        parent::executeIndex($request);
    }

    protected function buildQuery() {
        $query = parent::buildQuery();
        $this->addSystemQuery($query);
        return $query;
    }


    private function addSystemQuery($query) {
        //过滤掉删除状态的记录
        $query->addWhere('r.status_id != ?', 1006);
    }


//添加视频
    public function executeAddSelectedVideosToGroup(sfWebRequest $request) {
        $videoIds = $request->getParameter('videoIds');
        $videoGroupId = $request->getParameter('video_group_id');
        $currentGroupVideos = $this->getUser()->getAttribute('currentGroupVideos');
        if ($currentGroupVideos != null) {
            foreach ($videoIds as $videoId)
            {
                $video = Doctrine_Core::getTable('Video')->find($videoId);
                if (!in_array($video, $currentGroupVideos)) {
                    array_push($currentGroupVideos, $video);
                }
            }
        }
        $this->getUser()->setAttribute('currentGroupVideos', $currentGroupVideos);
        $this->group_videos = $currentGroupVideos;

        $this->video_group = Doctrine_Core::getTable('VideoGroup')->find($videoGroupId);
        $this->form = $this->configuration->getForm($this->video_group);
        $this->redirect(array('sf_route' => 'video_group_edit', 'sf_subject' => $this->video_group));
        $this->setTemplate('edit');
        //
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $notice = $form->getObject()->isNew() ? '添加视频组成功！' : '修改视频组成功！.';

            try {
                $video_group = $form->save();


                $this->getLogger()->log(" current video group Id:" . $video_group->getVideoGroupId());
                ///customized code//////////
                $oldGroupVideoIds = $this->getGroupVideoIdsByVideoGroup($video_group);
                $newGroupVideoIds = $request->getParameter('groupVideoIds');

                $this->getLogger()->log("group ids:" . $newGroupVideoIds);

                foreach ($oldGroupVideoIds as $oldVideoId) {

                    if (!in_array($oldVideoId, $newGroupVideoIds)) {
                        $this->getLogger()->log(" current old videoId:" . $oldVideoId);
                        $link = Doctrine_Core::getTable("GroupVideoLink")->find(array($video_group->getVideoGroupId(), $oldVideoId));
                        $link->delete();
                    }
                }

                $orderId = 1;
                foreach ($newGroupVideoIds as $videoId)
                {
                    $this->getLogger()->log(" current new  videoId:" . $videoId);
                    $link = Doctrine_Core::getTable("GroupVideoLink")->find(array($video_group->getVideoGroupId(), $videoId));
                    if ($link != null && $link->getOrderI() != $orderId) {
                        $this->getLogger()->log("update link,videoId:" . $videoId . " videoGroupId:" . $video_group->getVideoGroupId());
                        $link->setOrderI($orderId);
                        $link->save();

                    } else if ($link == null) {
                        $link = new GroupVideoLink();
                        $this->getLogger()->log("new link,videoId:" . $videoId . " videoGroupId:" . $video_group->getVideoGroupId());
                        $link->setVideoGroupId($video_group->getVideoGroupId());
                        $link->setVideoId($videoId);
                        $link->setOrderI($orderId);
                        $link->save();
                    }
                    $currVideo = Doctrine_Core::getTable("Video")->find($videoId);
                    if ($currVideo->getPrimVideoGroupId() != $video_group->getVideoGroupId()
                            || $currVideo->getPrimVideoGroupId() == NULL) {
                        $currVideo->setPrimVideoGroupId($video_group->getVideoGroupId());
                        $currVideo->save();
                    }

                    $orderId++;
                }


//                $video_group->setCreateTime(date("Y-m-d H:i:s"));
//                $video_group->setPublishTime(date("Y-m-d H:i:s"));
                $video_group->setStatusId(1004); //不审核状态
                $video_group->save();
                ////////////////////////////


            } catch (Exception $e)
            {
                $this->getLogger()->log("save failure:" . $e->getMessage() . " " . $e->getTraceAsString());
            }
            catch (Doctrine_Validator_Exception $e) {

                $errorStack = $form->getObject()->getErrorStack();

                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors) {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');

                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }

            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $video_group)));

            if ($request->hasParameter('_save_and_add')) {
                $this->getUser()->setFlash('notice', $notice . ' You can add another one below.');

                $this->redirect('@video_group_new');
            }
            else
            {
                $this->getUser()->setFlash('notice', $notice);

                $this->redirect(array('sf_route' => 'video_group_edit', 'sf_subject' => $video_group));
            }
        }
        else
        {
            $this->getUser()->setFlash('error', '视频组保存失败.', false);
        }
    }

    //移除选中视频
    public function executeRemoveSelectedVideoFromVideoGroup(sfWebRequest $request) {
        $videoId = $request->getParameter('videoId');
        $videoToBeRemoved = Doctrine_Core::getTable('Video')->find($videoId);
        $currentGroupVideos = $this->getUser()->getAttribute('currentGroupVideos');

        if ($currentGroupVideos != null) {
            $idx = 0;
            foreach ($currentGroupVideos as $video)
            {
                if ($video->getVideoId() == $videoId) {
                    array_slice($currentGroupVideos, $idx, 1);
                    break;
                }
                $idx++;
            }
            $this->getUser()->setAttribute('currentGroupVideos', $currentGroupVideos);
        }

        $this->video_group = $this->getRoute()->getObject();
        $this->form = $this->configuration->getForm($this->video_group);
        $this->redirect(array('sf_route' => 'video_group_edit', 'sf_subject' => $this->video_group));
        $this->setTemplate('edit');

    }


    //所有视频列表
    private function getAllVideos() {
        return Doctrine_Query::create()->from('Video')->execute();

    }


    //获取当前视频组视频列表
    private function getGroupVideos() {
        $currentGroupVideos = array();
        if ($this->video_group != null) {
            $links = $this->video_group->getGroupvideolink();
            foreach ($links as $link)
            {
                $currentGroupVideos[$link->getOrderI()] = $link->getVideo();
            }
            ksort($currentGroupVideos);
        }
        return $currentGroupVideos;

    }

    private function getGroupVideoIdsByVideoGroup(VideoGroup $videoGroup) {
        $groupVideos = array();
        if ($videoGroup != null) {
            $links = $videoGroup->getGroupVideoLink();
            foreach ($links as $link)
            {
                array_push($groupVideos, $link->getVideoId());
            }
        }
        return $groupVideos;
    }
}
